package com.tjetc.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class Db {
    private static DataSource dataSource = new ComboPooledDataSource();
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public static QueryRunner runner0(){
        return new QueryRunner(dataSource);
    }

    public static QueryRunner runner(){
        return new QueryRunner();
    }

    public static Connection getConnection(){
        Connection connection = threadLocal.get();
        if (connection==null) {
            //从数据库连接池中捞取连接
            try {
                connection =  dataSource.getConnection();
                threadLocal.set(connection);//将捞取到的connection对象与但当前的线程绑定
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 开启当前线程的事务
     */
    public static void startTransaction(){
        //先得到当前线程的连接对象
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(false);//设置手动提交
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交当前线程的事务
     */
    public static void commit(){
        Connection connection = getConnection();
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚当前线程的事务
     */
    public static void rollback(){
        Connection connection = getConnection();
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(){
        Connection connection = getConnection();
        try {
            connection.close();//还给数据库连接池，由数据库连接池控制
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            threadLocal.remove();
        }
    }
}
